/**
 * 
 */
package com.jeesuite.bestpl.rest.controller;

import java.io.InputStream;

import javax.inject.Singleton;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import org.apache.commons.io.IOUtils;
import org.glassfish.jersey.media.multipart.FormDataBodyPart;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataMultiPart;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.jeesuite.bestpl.exception.DemoBaseException;
import com.jeesuite.filesystem.spring.FSProviderSpringFacade;

/**
 * @description <br>
 * @author <a href="mailto:vakinge@gmail.com">vakin</a>
 * @date 2017年3月12日
 */
@Component
@Singleton
@Path("/attachment")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED })
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED})
public class AttachmentController {

	@Autowired
	@Qualifier("qiniuFSProvider")
	private FSProviderSpringFacade provider;
	
	@POST
	@Path("upload")
	@Consumes(MediaType.MULTIPART_FORM_DATA)
	public String uploadHeadImg(@Context HttpServletRequest request, FormDataMultiPart form){
		try {	
			//获取文件流  
		    FormDataBodyPart filePart = form.getField("file");   
		    //把表单内容转换成流  
		    InputStream fileInputStream = filePart.getValueAs(InputStream.class);
		    String catalog = request.getParameter("catalog");
		  
		    FormDataContentDisposition disposition = filePart.getFormDataContentDisposition();  
			String fileName = disposition.getFileName();  
			byte[] byteArray = IOUtils.toByteArray(fileInputStream);
			String url = provider.upload(catalog, fileName, byteArray, null);
			return url;
		} catch (Exception e) {
			throw new DemoBaseException(9999, e.getMessage());
		}
	}

}
